
package com.elong.common.http;

import java.util.concurrent.TimeUnit;

import org.apache.http.HttpClientConnection;
import org.apache.http.HttpHost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;




public class HttpConnectionManager {

    public static void postByRoute(){
        HttpClientContext context = HttpClientContext.create();
        @SuppressWarnings("resource")
        HttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
        HttpRoute route = new HttpRoute(new HttpHost("http://www.baidu.com"));
        // request new connection, this can be a long process
        ConnectionRequest connRequest = connMgr.requestConnection(route, null);
        // wait for connection up to 10 sec
        HttpClientConnection conn = null; 

        try {
            conn = connRequest.get(10, TimeUnit.SECONDS);
            // if not open
            if(!conn.isOpen()){
                //establish connection based on its route info
                connMgr.connect(conn, route, 1000, context);
                //and mark it as route complete
                connMgr.routeComplete(conn, route, context);
            }
            // do sueful thing with the connection
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            connMgr.releaseConnection(conn, null, 1, TimeUnit.MINUTES);
        }
        connMgr = null;
    }
    
    public static void multiManager(){
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //increase max total connection to 200
        cm.setMaxTotal(200);
        //increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);
        cm.close();
    }
}
